<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>承诺达标合格证管理系统</h2>
      <div class="current-time">{{ currentTime }}</div>
    </div>

    <!-- 查询条件 -->
    <el-row :gutter="20" class="query-section">
      <el-col :span="6">
        <el-form-item label="区县">
          <el-select v-model="queryParams.districtCode" placeholder="请选择区县" clearable>
            <el-option label="全部" value="" />
            <el-option label="郫都区" value="510104" />
            <el-option label="新都区" value="510114" />
            <el-option label="温江区" value="510115" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="年份">
          <el-select v-model="queryParams.year" placeholder="请选择年份">
            <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="月份">
          <el-select v-model="queryParams.month" placeholder="请选择月份" clearable>
            <el-option v-for="month in monthOptions" :key="month.value" :label="month.label" :value="month.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-col>
    </el-row>

    <!-- 统计图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <!-- 第一行 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>合格证开具数量统计</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('monthly')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="monthlyChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>主要农产品数量统计</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('product')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="productChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>每日合格证开具实时数据</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('daily')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="dailyChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>街道/镇合格证打印数量统计</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('street')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="streetChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>主体合格证开具数量排名</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('entity')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="entityChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>街道/镇用户数量统计</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('streetUser')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="streetUserChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getStatisticsOverview } from "@/api/monitor/njt/statistics/certificate";
import * as echarts from 'echarts';

export default {
  name: "Index",
  data() {
    return {
      currentTime: '',
      queryParams: {
        districtCode: '',
        year: new Date().getFullYear().toString(),
        month: ''
      },
      yearOptions: [],
      monthOptions: [
        { label: '1月', value: '1' },
        { label: '2月', value: '2' },
        { label: '3月', value: '3' },
        { label: '4月', value: '4' },
        { label: '5月', value: '5' },
        { label: '6月', value: '6' },
        { label: '7月', value: '7' },
        { label: '8月', value: '8' },
        { label: '9月', value: '9' },
        { label: '10月', value: '10' },
        { label: '11月', value: '11' },
        { label: '12月', value: '12' }
      ],
      charts: {},
      // 版本号
      version: "3.9.0"
    }
  },
  created() {
    this.initYearOptions();
    this.updateCurrentTime();
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
      this.getStatisticsData();
    });
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 清理事件监听器
    window.removeEventListener('resize', this.handleResize);
    
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });
  },
  methods: {
    // 初始化年份选项
    initYearOptions() {
      const currentYear = new Date().getFullYear();
      for (let i = currentYear; i >= currentYear - 5; i--) {
        this.yearOptions.push(i.toString());
      }
    },

    // 更新当前时间
    updateCurrentTime() {
      const now = new Date();
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      this.currentTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')} ${weekdays[now.getDay()]}`;
      
      // 每秒更新时间
      setTimeout(() => {
        this.updateCurrentTime();
      }, 1000);
    },

    // 获取统计数据
    getStatisticsData() {
      getStatisticsOverview(this.queryParams).then(response => {
        if (response.code === 200) {
          // 延迟更新图表，确保DOM已渲染
          setTimeout(() => {
            this.updateCharts(response.data);
          }, 100);
        }
      }).catch(error => {
        console.log('统计数据加载失败，使用模拟数据');
        // 延迟加载模拟数据
        setTimeout(() => {
          this.loadMockData();
        }, 100);
      });
    },

    // 加载模拟数据
    loadMockData() {
      const mockData = {
        monthlyStatistics: [
          { month: '2023-01', count: 4415 },
          { month: '2023-02', count: 16171 },
          { month: '2023-03', count: 17714 },
          { month: '2023-04', count: 23495 },
          { month: '2023-05', count: 22744 },
          { month: '2023-06', count: 18931 },
          { month: '2023-07', count: 12853 },
          { month: '2023-08', count: 4979 }
        ],
        productStatistics: [
          { productName: '生菜', count: 22153 },
          { productName: '韭黄', count: 6898 },
          { productName: '锦宁韭黄', count: 6000 },
          { productName: '儿菜', count: 5945 },
          { productName: '大蒜', count: 5784 },
          { productName: '海鲜菇', count: 5621 },
          { productName: '韭菜', count: 4109 },
          { productName: '茄子', count: 3892 },
          { productName: '苦瓜', count: 2946 },
          { productName: '丝瓜', count: 2936 }
        ],
        dailyStatistics: [
          { day: '01', count: 155 },
          { day: '02', count: 17 },
          { day: '03', count: 2026 },
          { day: '04', count: 24 },
          { day: '05', count: 975 },
          { day: '06', count: 3 },
          { day: '07', count: 1286 },
          { day: '08', count: 232 }
        ],
        streetStatistics: [
          { streetName: '广昌镇', count: 46509, percentage: 38.42 },
          { streetName: '安德街道', count: 37881, percentage: 31.23 },
          { streetName: '新桥街道', count: 28806, percentage: 23.75 },
          { streetName: '德源街道', count: 5200, percentage: 4.29 },
          { streetName: '友爱镇', count: 721, percentage: 0.59 },
          { streetName: '三道堰镇', count: 11, percentage: 0.01 },
          { streetName: '唐昌街道', count: 2079, percentage: 1.71 }
        ],
        entityStatistics: [
          { entityName: '天府新区成都片区太平遇见驿站家庭农场', count: 74819 },
          { entityName: '四川益康农业科技有限公司', count: 21716 },
          { entityName: '成都市新都区云桥蔬菜专业合作社', count: 19101 },
          { entityName: '成都林惠农业开发有限公司', count: 18828 },
          { entityName: '郫都区福源农场', count: 11550 },
          { entityName: '四川鑫农源农业发展有限公司', count: 9906 },
          { entityName: '成都汇众源生物科技有限公司', count: 9067 },
          { entityName: '成都甘露草莓种植专业合作社', count: 8197 },
          { entityName: '成都市天府新区鱼凫街道农艺竹业种植专业合作社', count: 8107 },
          { entityName: '成都市天府新区锦云顶农副产品营销专业合作社', count: 7739 }
        ],
        streetUserStatistics: [
          { streetName: '广昌镇', userCount: 58, percentage: 40.96 },
          { streetName: '安德街道', userCount: 45, percentage: 27.11 },
          { streetName: '新桥街道', userCount: 23, percentage: 13.86 },
          { streetName: '三道堰镇', userCount: 8, percentage: 4.82 },
          { streetName: '友爱镇', userCount: 5, percentage: 3.01 },
          { streetName: '红光街道', userCount: 4, percentage: 2.41 },
          { streetName: '德源街道', userCount: 5, percentage: 3.01 },
          { streetName: '团结街道', userCount: 8, percentage: 4.82 }
        ]
      };
      this.updateCharts(mockData);
    },

    // 查询
    handleQuery() {
      this.getStatisticsData();
    },

    // 重置
    resetQuery() {
      this.queryParams = {
        districtCode: '',
        year: new Date().getFullYear().toString(),
        month: ''
      };
      this.getStatisticsData();
    },

    // 初始化图表
    initCharts() {
      console.log('开始初始化图表...');
      
      // 确保DOM元素存在
      const monthlyEl = document.getElementById('monthlyChart');
      const productEl = document.getElementById('productChart');
      const dailyEl = document.getElementById('dailyChart');
      const streetEl = document.getElementById('streetChart');
      const entityEl = document.getElementById('entityChart');
      const streetUserEl = document.getElementById('streetUserChart');

      console.log('DOM元素检查:', {
        monthlyEl: !!monthlyEl,
        productEl: !!productEl,
        dailyEl: !!dailyEl,
        streetEl: !!streetEl,
        entityEl: !!entityEl,
        streetUserEl: !!streetUserEl
      });

      try {
        if (monthlyEl) {
          this.charts.monthly = echarts.init(monthlyEl);
          console.log('月度图表初始化成功');
        }
        if (productEl) {
          this.charts.product = echarts.init(productEl);
          console.log('产品图表初始化成功');
        }
        if (dailyEl) {
          this.charts.daily = echarts.init(dailyEl);
          console.log('每日图表初始化成功');
        }
        if (streetEl) {
          this.charts.street = echarts.init(streetEl);
          console.log('街道图表初始化成功');
        }
        if (entityEl) {
          this.charts.entity = echarts.init(entityEl);
          console.log('主体图表初始化成功');
        }
        if (streetUserEl) {
          this.charts.streetUser = echarts.init(streetUserEl);
          console.log('街道用户图表初始化成功');
        }
      } catch (error) {
        console.error('图表初始化失败:', error);
      }
    },

    // 更新图表
    updateCharts(data) {
      this.updateMonthlyChart(data.monthlyStatistics || []);
      this.updateProductChart(data.productStatistics || []);
      this.updateDailyChart(data.dailyStatistics || []);
      this.updateStreetChart(data.streetStatistics || []);
      this.updateEntityChart(data.entityStatistics || []);
      this.updateStreetUserChart(data.streetUserStatistics || []);
    },

    // 更新月度统计图表
    updateMonthlyChart(data) {
      if (!this.charts.monthly) return;
      
      const option = {
        title: {
          text: '合格证开具数量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.month)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: data.map(item => item.count),
          type: 'bar',
          itemStyle: {
            color: '#409EFF'
          }
        }]
      };
      this.charts.monthly.setOption(option);
    },

    // 更新农产品统计图表
    updateProductChart(data) {
      if (!this.charts.product) return;
      
      const option = {
        title: {
          text: '主要农产品数量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.productName),
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: data.map(item => item.count),
          type: 'bar',
          itemStyle: {
            color: function(params) {
              const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'];
              return colors[params.dataIndex % colors.length];
            }
          }
        }]
      };
      this.charts.product.setOption(option);
    },

    // 更新每日统计图表
    updateDailyChart(data) {
      if (!this.charts.daily) return;
      
      const option = {
        title: {
          text: '每日合格证开具实时数据',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.day + '日')
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: data.map(item => item.count),
          type: 'bar',
          itemStyle: {
            color: '#67C23A'
          }
        }]
      };
      this.charts.daily.setOption(option);
    },

    // 更新街道统计图表
    updateStreetChart(data) {
      if (!this.charts.street) return;
      
      const option = {
        title: {
          text: '街道/镇合格证打印数量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '合格证数量',
          type: 'pie',
          radius: '50%',
          data: data.map(item => ({
            value: item.count,
            name: item.streetName
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      this.charts.street.setOption(option);
    },

    // 更新主体统计图表
    updateEntityChart(data) {
      if (!this.charts.entity) return;
      
      const option = {
        title: {
          text: '主体合格证开具数量排名',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: data.map(item => item.entityName.length > 10 ? item.entityName.substring(0, 10) + '...' : item.entityName)
        },
        series: [{
          data: data.map(item => item.count),
          type: 'bar',
          itemStyle: {
            color: '#E6A23C'
          }
        }]
      };
      this.charts.entity.setOption(option);
    },

    // 更新街道用户统计图表
    updateStreetUserChart(data) {
      if (!this.charts.streetUser) return;
      
      const option = {
        title: {
          text: '街道/镇用户数量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '用户数量',
          type: 'pie',
          radius: '50%',
          data: data.map(item => ({
            value: item.userCount,
            name: item.streetName
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      this.charts.streetUser.setOption(option);
    },

    // 下载图表
    downloadChart(type) {
      if (this.charts[type]) {
        const url = this.charts[type].getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff'
        });
        const link = document.createElement('a');
        link.download = `${type}_chart.png`;
        link.href = url;
        link.click();
      }
    },

    goTarget(href) {
      window.open(href, "_blank")
    },

    // 处理窗口大小变化
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.current-time {
  font-size: 16px;
  font-weight: 500;
}

.query-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  padding: 10px;
}

.el-form-item {
  margin-bottom: 0;
}

.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
</style>

